package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 商品上架、下架
     *
     * @param id
     * @param status 根据id修改商品状态
     */
    @Transactional
    @Override
    public void updateStatus(Long id, Integer status) {

        // 法一：使用itemMapper方法
        /*Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        ItemMapper itemMapper = this.baseMapper;
        itemMapper.updateById(item);*/

        // update tb_item set status = ? where id =?
        // 法二：使用itemService

        this.update().set("status", status).eq("id", id).update();
        String routingKey;
        if (status == 1) {
            routingKey = "item.up";
        } else {
            routingKey = "item.down";
        }
        rabbitTemplate.convertAndSend("item.topic", routingKey, id);

        // String routingKey = status == 1 ? "item.up" : "item.down";

    }

    /**
     * 扣减库存
     *
     * @param itemId
     * @param num
     */
    @Transactional
    @Override
    public void deductStock(Long itemId, Integer num) {
        // update tb_item set stock = stock - #{num} where id = #{itemId}
        try {
            update().setSql("stock = stock - " + num)
                    .eq("id", itemId).update();
        } catch (Exception e) {
            throw new RuntimeException("库存不足");
        }
    }
}
